package com.sysfrog.cucumber;

/*
* Copyright (C) 2010 Thomas Heggelund
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*
*/

import com.intellij.lang.ASTNode;
import com.intellij.lang.folding.FoldingBuilder;
import com.intellij.lang.folding.FoldingDescriptor;
import com.intellij.openapi.editor.Document;
import com.intellij.psi.PsiElement;
import com.sysfrog.cucumber.lexer.CucumberTokenTypesNew;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import static com.sysfrog.cucumber.lexer.CucumberTokenTypesNew.MY_SCENARIO;
import static com.sysfrog.cucumber.lexer.CucumberTokenTypesNew.MY_TABLE;
import static com.sysfrog.cucumber.psi.CucumberElementTypes.FILE;

public class CucumberFoldingBuilder implements FoldingBuilder {

    public String getPlaceholderText(ASTNode node) {
        if (node.getElementType() == MY_SCENARIO || node.getElementType() == MY_TABLE ) {
            PsiElement def = node.getPsi();
            return node.getText().split("\\n")[0] + "\n";
        } 
        return null;
    }

    public boolean isCollapsedByDefault(@NotNull ASTNode node) {
        return (node.getElementType() == CucumberTokenTypesNew.MY_SCENARIO || node.getElementType() == CucumberTokenTypesNew.MY_TABLE );
    }

    public FoldingDescriptor[] buildFoldRegions(ASTNode node, Document document) {
        touchTree(node);
        List<FoldingDescriptor> descriptors = new ArrayList<FoldingDescriptor>();
        appendDescriptors(node, descriptors);
        return descriptors.toArray(new FoldingDescriptor[descriptors.size()]);
    }

    private void touchTree(ASTNode node) {
        if (node.getElementType() == FILE) {
            final PsiElement firstChild = node.getPsi().getFirstChild();
        }
    }

    private void appendDescriptors(final ASTNode node, final List<FoldingDescriptor> descriptors) {
        if (isFoldableNode(node)) {
            descriptors.add(new FoldingDescriptor(node, node.getTextRange()));
        }

        ASTNode child = node.getFirstChildNode();
        while (child != null) {
            appendDescriptors(child, descriptors);
            child = child.getTreeNext();
        }
    }

    private boolean isFoldableNode(ASTNode node) {
        return  (node.getElementType() == MY_SCENARIO || node.getElementType() == MY_TABLE);
    }
}

